<template>
  <div class="app-container">
    <auto-record-filter @on-filter="submitFilterForm"/>
    <div style="padding: 20px 0; display: flex">
      <el-button-group>
        <el-button size="mini" type="primary" v-if="roleCheck('auto-record-export')" icon="el-icon-download"
                   @click="exportHandle(1)" :loading="downLoadLoading">{{$t('language.table.export')}}
        </el-button>
      </el-button-group>
      <div class="down-percentage" v-show="showDownPercentage">
        <span>报表导出中：</span>
        <el-progress :percentage="percentage"></el-progress>
      </div>
    </div>
    <el-table :data="tableData.list" height="500" v-loading="loading" element-loading-text="加载中..."
              class="el-table-align-center">
      <el-table-column :label="$t('language.finance.withdrawal.requestTime')" width="90" prop="userType" align="center">
        <template slot-scope="{row}">
          <div>{{row.createDate | toTime}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.billNo')" width="100" prop="userType" align="center">
        <template slot-scope="{row}">
          <div :class="{'active': row.splitStatus == 1}">{{row.orderId}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.thirdPartyWithdrawalBillNo')" width="110"
                       prop="thirdOrderId" align="center"></el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.splitRelatedTxn')" prop="batchNumber" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.accountType')" prop="userType" align="center">
        <template slot-scope="{row}">
          {{toSwitchData('language.finance.consts.USER_TYPE', row.userType)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.withdrawalType')" align="center">
        <template slot-scope="{row}">
          {{toSwitchData('language.finance.consts.WITHDRAW_TYPE', row.aisleType)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.paymentType')" prop="withdrawType" align="center">
        <template slot-scope="{row}">
          {{toSwitchData('language.finance.consts.PAYMENT_TYPE', row.withdrawType)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.level')" prop="userLevel" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.accountName')" prop="username" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.name')" prop="reallyName" align="center">
      </el-table-column>
      <el-table-column sortable :label="$t('language.finance.withdrawal.amount')" width="100" prop="amount"
                       align="center">
        <template slot-scope="{row}">
          {{row.amount | currency}}
        </template>
      </el-table-column>
      <el-table-column sortable :label="$t('language.finance.withdrawal.fee')" width="90" prop="fee" align="center">
        <template slot-scope="{row}">
          {{row.fee | currency('', 2, {type: 1})}}
        </template>
      </el-table-column>
      <el-table-column :sortable="true" :sort-by="formatter"
                       :label="$t('language.finance.withdrawal.payoutConfirmation')" width="100" prop="moneyCheck"
                       align="center">
        <template slot-scope="{row}">
          {{(row.paragraph) | currency}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.customersWithdrawbankName')" align="center">
        <el-table-column :label="$t('language.finance.withdrawal.customersWithdrawbankName')" prop="bankName"
                         width="100" align="center">
        </el-table-column>
        <el-table-column :label="$t('language.finance.withdrawal.bankCard')" prop="cardNo" width="150" align="center">
          <template slot-scope="{row}">
            <span class="clipboard-btn" :data-clipboard-text="row.cardNo">{{row.cardNo}}</span>
          </template>
        </el-table-column>
        <!--<el-table-column label="开户行地址" prop="address" width="120" align="center">-->
        <!--</el-table-column>-->
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.userName')" width="90" prop="name" align="center">
        <template slot-scope="{row}">
          <span class="clipboard-btn" :data-clipboard-text="row.name">{{row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.payoutMerchant')" width="90" prop="merchant"
                       align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.payoutMerchantID')" width="90" prop="merchantCode"
                       align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.operationEnd')" prop="clientType" align="center">
        <template slot-scope="{row}">
          {{row.clientType | toConverter('PAYMENT_PLATFORM')}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.thePayee')" width="120" prop="approver" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.payoutTime')" width="90" prop="approveTime"
                       align="center">
        <template slot-scope="{row}">
          {{row.approveTime| toTime}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.handler')" width="120" prop="seperator" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.dispenser')" width="120" prop="seperateCreator"
                       align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.dispenseTime')" width="90" prop="seperateDate"
                       align="center">
        <template slot-scope="{row}">
          {{row.seperateDate | toTime}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.riskHandler')" width="90" prop="riskApprover"
                       align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.riskControlApprovalTime')" width="90" prop="riskApvTime"
                       align="center">
        <template slot-scope="{row}">
          {{row.riskApvTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.status')" width="100" prop="status" align="center">
        <template slot-scope="{row}">
          {{ toSwitchData('language.finance.consts.WITHDRAW_STATUS_TWO_RECORD', row.status) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.reasonsForRefusal')" width="100" align="center">
        <template slot-scope="{row}">
          {{row.rejectReason}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.remarks')" width="150" align="center">
        <template slot-scope="{row}">
          {{row.status === -2?row.riskApvRemark:row.remark}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.label')" width="150" prop="tag" align="center">
      </el-table-column>
    </el-table>
    <div style="font-size:12px;margin-top:30px;color:grey;">
      <span>注1：提现拆过单的提现单号，会以淡棕底色显示；在注单筛选位置输入注单号并勾选关联拆单搜索，即可筛选出晒单相关联的注单</span><br>
      <span>注2：若是一笔人工出款单拆单后进入了不同的页面（审核等等）则可以在相关联的位置进行注单关联搜索</span><br>
      <span>注3：拆单关联号说明，例子：1-2-1（1-代表单个会员拆单数，2-代表此单一共拆成几个提现单，1-代表拆单中的第几单），拆单关联号号码以天为周期</span>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>
    <normal-withdraw-dialog
      v-if="dialogName === 'normal-withdraw-dialog'"
      v-model="dialogVisible"
      :id="dialogProps.id"
      :row-data="dialogProps"
      :step="step"
      @submit="submitFinished"/>

    <auto-withdraw-dialog
      v-if="dialogName === 'auto-withdraw-dialog'"
      v-model="dialogVisible"
      :id="dialogProps.id"
      :row-data="dialogProps"
      :step="step"
      @submit="submitFinished"/>
  </div>
</template>


<script>
import {getWithdrawList, exportAutoRecord} from '@/services/api/withdraw';
import {
  grid, constsLabel, dialog, handleDownload, switchData,
} from '@/build';
import AutoRecordFilter from '@/views/finance/withdraw/autoRecordFilter';
import NormalWithdrawDialog from '@/views/finance/withdraw/normalWithdrawDialog';
import AutoWithdrawDialog from '@/views/finance/withdraw/autoWithdrawDialog';

export default {
  name: 'withdraw-normal',
  components: {NormalWithdrawDialog, AutoRecordFilter, AutoWithdrawDialog},
  mixins: [grid, constsLabel, dialog, handleDownload, switchData],
  data() {
    return {
      activeClass: 'active',
      tableData: {},
      rowData: {},
      filters: {
        size: 20,
        page: 1,
        withdrawType: -1,
        status: [1, 2, 8, -2, 4, 5, 9],
        startTime: moment().format('YYYY-MM-DD 00:00:00'),
        endTime: moment().format('YYYY-MM-DD 23:59:59'),
        userLevel: [],
        dateType: 1,
        searchType: 2,
        splitStatus: -1,
      },
      dialogVisible: false,
      step: 'agree',
      percentage: 0,
      showDownPercentage: false,
      exportData: [],
      downLoadLoading: false,
    };
  },
  methods: {
    toStatus(val) {
      return _.find(this.$t('language.finance.consts.WITHDRAW_STATUS_TWO_RECORD'), {value: val}).title;
    },
    setStep(step) {
      this.step = step;
    },
    formatter(row, column) {
      return row.paragraph;
    },
    async exportHandle(page = 1) {
      const {
        fromDate, endDate, withdrawType, bankId, dateType, searchType, keywords, merchant, clientType, userType, cardNo, maxAmount, minAmount, startTime, endTime,
      } = this.filters;
      const size = 5000;
      const status = this.filters.status.join(',');
      const ajaxData = {
        fromDate,
        endDate,
        withdrawType,
        bankId,
        status,
        dateType,
        searchType,
        keywords,
        merchant,
        clientType,
        userType,
        cardNo,
        maxAmount,
        minAmount,
        startTime,
        endTime,
        page,
        size,
      };
      this.downLoadLoading = true;
      this.showDownPercentage = true;
      const filename = '出款记录报表.csv';
      // const header = ['提现时间', '提现单号', '第三方提现单号', '拆单关联号', '账户类型', '提现类型', '出款类型', '层级', '账户名', '姓名', '提现金额', '手续费', '出款确认', '银行名称', '卡号', '用户姓名', '出款商户', '出款商户号', '操作端', '出款人', '出款时间', '处理人', '分单人', '分单时间', '风险处理人', '风控处理时间', '状态', '拒绝理由', '备注', '标签'];
      // const filterField = ['createDate', 'orderId', 'thirdOrderId', 'batchNumber', 'userType', 'aisleType', 'withdrawType', 'userLevel', 'username', 'reallyName', 'amount', 'fee', 'paragraph', 'bankName', 'cardNo', 'name', 'merchant', 'merchantCode', 'clientType', 'approver', 'approveTime', 'seperator', 'seperateCreator', 'seperateDate', 'riskApprover', 'riskApvTime', 'statusText', 'rejectReason', 'newRemark', 'tag'];
      const header = ['提现时间', '提现单号', '层级', '账户名', '提现金额', '手续费', '出款确认金额', '出款时间', '用户姓名', '出款商户',
        '出款商户号', '出款银行', '出款卡姓名', '出款类型', '出款卡号', '备注'];
      const filterField = ['createDate', 'orderId', 'userLevel', 'username', 'amount', 'fee', 'paragraph', 'approveTime', 'name', 'merchant',
        'merchantCode', '', '', 'withdrawType', 'transferBankCardNo', 'newRemark'];
      const [result, data] = await exportAutoRecord(ajaxData);
      if (result) {
        if (data && data.list.length > 0) {
          const allPage = Math.ceil(data.total / size);
          this.exportData = [...this.exportData, ...this.responseFormatter(data.list)];
          this.percentage = (page / allPage).toFixed(2) * 100;
          if (page < allPage) {
            this.exportHandle(page + 1);
          } else {
            this.export2Excel(header, filterField, this.exportData, filename);
            this.exportData = [];
            setTimeout(() => {
              this.initDownLoad();
            }, 1000);
          }
        } else {
          this.$message({message: `导出内容为空，请从新选择`, type: 'warning'});
          this.initDownLoad();
        }
      } else {
        this.$message({message: `导出失败,${data.message}`, type: 'warning'});
        this.initDownLoad();
      }
    },
    initDownLoad(){
      this.showDownPercentage = false;
      this.percentage = 0;
      this.downLoadLoading = false;
    },
    responseFormatter(data) {
      data.map((item) => {
        const paragraph = item.amount - item.fee;
        item.createDate = _.toTime(item.createDate);
        // item.userType = _.toConverter(item.userType, 'ACCOUNT_TYPE');
        // item.clientType = _.toConverter(item.clientType, 'PAYMENT_PLATFORM');
        item.withdrawType = _.toConverter(item.withdrawType, 'OUT_TYPE_PAY');
        item.amount = _.currency(item.amount);
        item.fee = (parseInt((item.fee) * 100) / 100).toFixed(2);
        item.paragraph = _.currency(paragraph);
        // item.sucApvTime = _.toTime(item.sucApvTime);
        // item.riskApvTime = _.toTime(item.riskApvTime);
        // item.seperateDate = _.toTime(item.seperateDate);
        item.approveTime = _.toTime(item.approveTime);
        // item.statusText = _.toConverter(item.status, 'WITHDRAW_STATUS_TWO_RECORD');
        // item.aisleType = _.toConverter(item.aisleType, 'AISLE_TYPE');
        item.newRemark = item.status === -2 ? item.riskApvRemark : item.remark;
      });

      return data;
    },
    formatPercentage(percentage) {
      if (percentage === 100) {
        setTimeout(() => {
          this.showDownPercentage = false;
        }, 1000);
      }
      return percentage === 100 ? '下载完成' : `${percentage}%`;
    },
  },
  mounted() {
    // tab页记录访问日志
    this.$store.dispatch(types.SAVE_OPERATION_LOG, {content: _.getContent(this.$route, '正常提现-三方手动出款', true)});
    this.bindGet(getWithdrawList, 'tableData', {
      action: 'getGrid',
      beforeSend: (data) => {
        if (data.splitType) {
          data.splitType = 1;
        } else {
          data.splitType = undefined;
        }
        if (data.status.length > 0) {
          data.status = data.status.join(',');
        }
        if (data.userLevel.length > 0) {
          data.userLevel = data.userLevel.join(',');
        }
        delete data.time;
        return data;
      },
      sendingData: 'filters',
      format: (data) => {
        data.list.forEach((v, k) => {
          this.$set(v, 'paragraph', v.amount - v.fee);
        });
        return data;
      },
    });
    this.doGet({action: 'getGrid'});
  },
};
</script>

<style scoped lang="scss">
  .active {
    color: #F4A460;;
  }

  /deep/ thead .cell {
    word-break: break-word;
  }
  .down-percentage{
    width: 200px;
  }
</style>
